package com.sdry.web.controller.jyy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.Receive;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.jyy.TrayLocation;
import com.sdry.model.jyy.Up;
import com.sdry.model.jyy.Workload;
import com.sdry.model.llm.LlmWarehouseStock;
import com.sdry.model.lz.BarCodeConversionRecord;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.ReceiveMark;
import com.sdry.model.tdd.emailRecord.EmailRecord;
import com.sdry.model.zc.ZcGeneralQueryEntity;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ErrorServise;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.jyy.ReceiveService;
import com.sdry.service.jyy.UpService;
import com.sdry.service.jyy.unpack.UnpackDetalService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.llm.DevaningWorkService;
import com.sdry.service.llm.InquiryBusinessService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.tdd.UnpackingService;
import com.sdry.service.tdd.emailRecord.EmailRecordService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.service.zc.ZcInventoryManagementService;
import com.sdry.service.zc.ZcSimplificationInService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;

/**
 * 收货和入库的app接口
 * @author jyy
 * @2019-05-16 14:15:38
 * LZ修改记录
 * 1、lz2019年11月5日在77行引入log，在2019年11月7日78行引入AFFECT_ROW变量，79引入AFFECT_ROW_STRING变量；
 * 2、110行左右新增warehouse_id字段；351行左右新增warehouse_id字段，
 * 3、拆分submitReceive接口，拆分为imgUpload(190行左右)、insertCustomerCode(225行左右)、insertEmailInfo(260行左右)方法，在submitReceive里调用；
 * 
 * 修改人：连雷明
 * 修改时间：2019-11-08
 * 修改内容：给方法submitReceipt，1730-1732行，加参数，仓库ID
 */
@RequestMapping("/app")
@Controller
public class AppJyController {
	private final static Logger log = LoggerFactory.getLogger(AppJyController.class);
	private final static int AFFECT_ROW = 0;
	//图片上传路径
	String imgLog = "";
	@Resource ReceiveService ReceiveService;
	@Resource ReceiveDetailService ReceiveDetailService;
	@Resource InquiryBusinessService inquiryBusinessService;
	@Resource UpService upService;
	@Resource ZcInventoryManagementService zcInventoryManagementService;
	@Resource UnpackingService unpackingService;
	@Resource MaterielService materielService;
	@Resource ZcBindAndUnbindService zcBindAndUnbindService;
	@Resource CancellingStockDetailService cancellingStockDetailService;
	@Resource DevaningWorkService devaningWorkService;
	@Resource ZcSimplificationInService zcSimplificationInService;
	@Resource BarCodeOperationService barCodeOperationService;
	@Resource InventoryService inventoryService;
	@Resource StockOutOrderService stockOutService;
	@Resource UnpackDetalService unpackDetalService;
	@Resource ErrorServise errorServise;
	@Resource EmailRecordService emailRecordService;

    /**
     * APP查询所有未收货的收货单
     * @param warehouse_id 仓库id
     * @param isSimple 0：条码收货 1：精简收货 2：批量收货
     * @param response
     */
	@RequestMapping("/selectAllReceive")
	public void selectAllReceive(String warehouse_id, String isSimple, HttpServletResponse response) {
		//LZ新增仓库id字段
		//Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		//Receive param = new Receive();
		//未收货
		//param.setState(AFFECT_ROW);
		//param.setIsSimple("0");
		//LZ添加warehouse_id
		//param.setWarehouse_id(Long.valueOf(warehouse_id));
		//List<Receive> list = ReceiveService.queryAllByMution(param);
		//int count = list.size();
        List<Receive> recieveList = ReceiveService.selectAllReceive(warehouse_id, isSimple);
        JSONObject jsonObject = new JSONObject();
		if (recieveList.size() > AFFECT_ROW) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", recieveList);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    //jsonObject.put("data", null);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("lz进入给app查询所有未收货的收货单的方法出现异常");
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据收货单号查询收货详情
	 * @param receiveNumber 收货单号
	 * @param response 响应
	 */
	@RequestMapping("/selectReceiveDtailByNumber")
	public void selectReceiveDtailByNumber(String receiveNumber, HttpServletResponse response, HttpSession session) {
        //List<Receive> receiveListSub = ReceiveDetailService.queryReceiveSubmitStatus(receiveNumber);
		log.info("lz进入根据收货单号查询收货详情的方法:receiveNumber=" + receiveNumber);
		ReceiveDetail param = new ReceiveDetail();
		//int count =0;
		List<ReceiveDetail> receiveDetailList = new ArrayList<>();
		//根据收货单号查询单据合并标识，如果有标识就查询标识单号所有的详细，没有就查询当前单号的详细
		String mergeFlag = ReceiveDetailService.queryMergeFlag(receiveNumber);
		if (mergeFlag != null) {
			/*String splitReceiveNumber[] = mergeFlag.split(",");
			for (String string : splitReceiveNumber) {
				param.setReceiveNumber(string);
				receiveDetailList = ReceiveDetailService.queryAllByMution(param);
				count = receiveDetailList.size();
			}*/
			//根据单据合并标识查询收货单详细
            receiveDetailList = ReceiveDetailService.queryReceiveByMergeFlag(mergeFlag);
		} else {
			param.setReceiveNumber(receiveNumber);
			receiveDetailList = ReceiveDetailService.queryAllByMution(param);
			//count = receiveDetailList.size();
		}
        /*for (ReceiveDetail receiveDetail:receiveDetailList) {
            receiveDetail.setSubmitStatus(receiveListSub.get(0).getSubmitStatus());
        }*/
		JSONObject jsonObject = new JSONObject();
		if (receiveDetailList.size() > AFFECT_ROW) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", receiveDetailList);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    //jsonObject.put("data", receiveDetailList);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("lz根据收货单号查询收货详情的方法出现异常");
			e.printStackTrace();
		}
	}
	
	/**
	 * 图片上传
	 * @param session session
	 * @param pic_key 图片上传文件名
	 */
	public void imgUpload(HttpSession session, List<MultipartFile> pic_key) {
		if(pic_key.size() > AFFECT_ROW){
			for(MultipartFile f : pic_key){
				if(f != null){
					// 1.获取原文件名1
					String oriName = f.getOriginalFilename();
					// 2.获取原文件图片后缀，以最后的.作为截取(.jpg)1
					String extName = oriName.substring(oriName.lastIndexOf("."));
					// 3.生成自定义的新文件名，这里以UUID.jpg|png|xxx作为格式（可选操作，也可以不自定义新文件名）1
					String uuid = UUID.randomUUID().toString();
					//组合成新的文件
					String newName = uuid + extName;
					// 4.获取要保存的路径文件夹
					String realPath = session.getServletContext().getRealPath("/images/");
					// 5.保存
					String savePath = realPath + "\\" +  newName;
					imgLog = "/images/" + newName;
					File desFile = new File(savePath);
					try {
						f.transferTo(desFile);
					} catch (Exception e) {
						log.info("LZ图片上传的方法出现异常");
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	/**
	 * 如果是供应商码，把条码存入receiveMark表
	 * @param warehouse_id 仓库id
	 * @param receiveDetailList 收货详情集合
	 */
	public void insertCustomerCode(Long warehouse_id, List<ReceiveDetail> receiveDetailList) {
		log.info("如果是供应商码，把条码存入receiveMark表的仓库id=" + warehouse_id);
		String receiveNumber = receiveDetailList.get(0).getReceiveNumber();
		Receive receive = new Receive();
		receive.setReceiveNumber(receiveNumber);
		//lz新增warehouse_id
		receive.setWarehouse_id(warehouse_id);
		List<Receive> list = ReceiveService.queryAllByMution(receive);
		if(list.size() > AFFECT_ROW){
			int bt = list.get(0).getBarcode();
			if(bt == 1){
				for (ReceiveDetail receiveDetail : receiveDetailList) {
					for (CodeMark cm : receiveDetail.getReceiveCode()) {
						ReceiveMark receiveMark = new ReceiveMark();
						receiveMark.setCode(cm.getCode());
						receiveMark.setNum(cm.getNum());
						receiveMark.setReceive_detail_id(receiveDetail.getId());
						receiveMark.setSAP_QAD(receiveDetail.getMateriel_num());
						//lz新增warehouse_id
						receiveMark.setWarehouse_id(warehouse_id);
						ReceiveDetailService.addReceiveMark(receiveMark);
					}
				}
			}
		}
	}
	
	/**
	 * 将邮件推送信息存入数据库
	 * @param warehouse_id
	 * @param materiel 物料实体
	 * @param zcInventoryInfoEntity 库存实体
	 */
	public void insertEmailInfo(Long warehouse_id, Materiel materiel, ZcInventoryInfoEntity zcInventoryInfoEntity) {
		//如果库存大于或小于预警值  报警
		String content = "";
		if (materiel != null) {
			String materiel_num = materiel.getMateriel_num();
			//String materiel_name = materiel.getMateriel_name();
			//String people = "";
			
			if(zcInventoryInfoEntity.getmNum() != null && materiel.getUpper_value() != null) {
				if (zcInventoryInfoEntity.getmNum() >= materiel.getUpper_value()) {
					content = materiel_num + "库存" + zcInventoryInfoEntity.getmNum() + "大于等于" + materiel.getUpper_value() + "特此报警";
					//PushExample.testSendPush(content , "库存报警", people, "0");
				} else if (zcInventoryInfoEntity.getmNum() <= materiel.getLower_value()) {
					content = materiel_num + "库存" + zcInventoryInfoEntity.getmNum() + "低于等于" + materiel.getLower_value() + "特此报警";
					//PushExample.testSendPush(content , "库存报警", people, "0");
				}
				
				//根据供应商id查询供应商的邮箱
				Customer customer = upService.queryCustomerEmailById(materiel.getCustomer_id());
				if (customer != null && !"".equals(content)) {
					EmailRecord emailRecord = new EmailRecord();
					emailRecord.setOperate("入库");
					emailRecord.setReceivePeopleId(customer.getId());
					emailRecord.setReceiveDate(DateUtil.dateFormat3());
					emailRecord.setEmailContent(content);
					emailRecord.setRemark("0");
					//lz新增warehouse_id
					emailRecord.setWarehouse_id(warehouse_id);
					//4、将邮件推送信息存入数据库
					emailRecordService.insert(emailRecord);
				}
			}
		}
	}
	
	/**
	 * APP收货提交的接口，lz2019年11月4日 15:30:19修改
	 * @param Details app扫描的收货单详细
	 * @param person 提交人(操作人)id
	 * @param sure_name 
	 * @param pic_key 图片上传路径
	 * @param response
	 * @param session
	 */
	@RequestMapping("/submitReceive")
	public void submitReceive(String Details, String person, List<MultipartFile> pic_key,
			String sure_name, HttpServletResponse response, String warehouse_id, HttpSession session, String appSubmitStatus) {
		Integer affect = upService.submitReceive(Details, person, pic_key, sure_name, Long.parseLong(warehouse_id), session, appSubmitStatus);
		JSONObject jsonObject = new JSONObject();
		if (affect == 0) {
            jsonObject.put("status", "0");
            jsonObject.put("message", "条码已存在，请勿重复提交！");
        } else if (affect == -1) {
            jsonObject.put("status", "0");
            jsonObject.put("message", "质检表新增数据失败！");
        } else if (affect == -2) {
            //传递数据到页面
            jsonObject.put("status", "0");
            jsonObject.put("message", "条码已存在，请勿重复提交！");
        } else if (affect == -3) {
            //传递数据到页面
            jsonObject.put("status", "0");
            jsonObject.put("message", "供应商条码表新增数据失败！");
        } else if (affect == -4) {
            //传递数据到页面
            jsonObject.put("status", "0");
            jsonObject.put("message", "修改库存表数据失败！");
        } else if (affect == -5) {
            //传递数据到页面
            jsonObject.put("status", "0");
            jsonObject.put("message", "修改收货单详细表数据失败！");
        } else if (affect == -6) {
            //传递数据到页面
            jsonObject.put("status", "0");
            jsonObject.put("message", "收货上架失败！");
        } else if (affect == -7) {
            //传递数据到页面
            jsonObject.put("status", "0");
            jsonObject.put("message", "上架到待检区失败！");
        } else if (affect == -8) {
            //传递数据到页面
            jsonObject.put("status", "0");
            jsonObject.put("message", "不允许多人同时操作一个收货单！");
        } else {
            //传递数据到页面
            jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
        }

		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("APP的收货提交方法出现异常");
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据物料id查询，存放该物料的仓库、库区、库位信息
	 * @param mid 物料id
	 * @param response 响应
	 * @throws Exception 
	 */
	@RequestMapping("/selectWarehouseByMid")
	public void selectWarehouseByMid(String mid, String customer, HttpServletResponse response) throws Exception {
		Up up = new Up();
		//物料id
		if(mid != null && mid != "") {
			up.setMid(Long.valueOf(mid));
		}
		//供应商id
		if(customer != null) {
			up.setCustomerId(Long.valueOf(customer));
		}
		List<LlmWarehouseStock> list = new ArrayList<LlmWarehouseStock>();
		
		if(mid != null && mid != "") {
			list = ReceiveService.selectWarehouseByMid(up);
		}else {
			list = inquiryBusinessService.appGetStock();
		}
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	
	/**
	 * 质检后的条码绑定
	 * @param json 质检后的条码绑定
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/comeku")
	public void comeku(String json, String person, HttpServletResponse response, String warehouse_id) {
		String addStr = "";
		Long affact = 0L;
		Gson gson = new Gson();
		List<ReceiveDetailQuality> receiveDetailQualityList = gson.fromJson(json, new TypeToken<List<ReceiveDetailQuality>>() {}.getType());
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
			for (int j = 0; j < receiveDetailQuality.getReceiveCode().size(); j++) {
				CodeMark exitCodeMark = ReceiveDetailService.queryCodeMarkByCode(receiveDetailQuality.getReceiveCode().get(j));
				if (exitCodeMark != null) {
					//根据精准码修改质检区库存的数量
					/*ReceiveDetailService.updateInventoryInfoQuality(receiveDetailQuality.getMid() + "", 
							receiveDetailQuality.getPici(), (exitCodeMark.getNum() - receiveDetailQuality.getReceiveCode().get(j).getNum()) + "");*/
					CodeMark codeMark = new CodeMark();
					codeMark.setCode(exitCodeMark.getCode());
					codeMark.setNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
					//传入查询到的条码和提交的数量
					affact = ReceiveDetailService.updateCodeMark(codeMark);
				} else {
					CodeMark codeMark = new CodeMark();
					codeMark.setReceive_detail_id(receiveDetailQuality.getId());
					codeMark.setCode(receiveDetailQuality.getReceiveCode().get(j).getCode());
					codeMark.setNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
					codeMark.setIs_ng(receiveDetailQuality.getReceiveCode().get(j).getIs_ng());
					//添加每种物料对应的多个条码
					ReceiveDetailService.addCodeMark(receiveDetailQuality.getReceiveCode().get(j));
					addStr += receiveDetailQuality.getReceiveCode().get(j).getCode() + ",";
				}
				//绑定后修改质检的状态为2
				ReceiveDetailService.updateReceiveDetailQuality2(receiveDetailQuality.getId() + "");
				//拆箱
				//ReceiveDetailService.uncomeku(code);
			}
		}
		//质检后同步质检区
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		zcMaterielAndTrayEntity.setMateriel_code(addStr);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion("待上架区");
		//zcMaterielAndTrayEntity.setTray_code(tray_code);
		//zcMaterielAndTrayEntity.setLocation_code(location_code);
		int affact2 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity, Long.parseLong(warehouse_id));
		JSONObject jsonObject = new JSONObject();
		if (affact > AFFECT_ROW) {
			//传递数据到页面
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "提交成功");
		} else {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交失败");
			jsonObject.put("data", "0");
		}
		
		//----------------------给历史记录表插入数据   start-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
			for (int j = 0; j < receiveDetailQuality.getReceiveCode().size(); j++) {
				BarCodeOperation bar = new BarCodeOperation();
				bar.setBarCode(receiveDetailQuality.getReceiveCode().get(j).getCode());
				bar.setCodeNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
				bar.setBatch(receiveDetailQuality.getPici());
				bar.setOperator(Long.parseLong(person));
				bar.setOperatingTime(time);
				bar.setMaterielId(receiveDetailQuality.getMid());
				bar.setType("质检");
				//lz新增warehouse_id
				bar.setWarehouse_id(Long.parseLong(warehouse_id));
				if(affact > AFFECT_ROW){
					bar.setResult("成功");
				} else {
					bar.setResult("失败");
				}
				barCodeOperationService.insert(bar);
			}
		}
		//----------------------给历史记录表插入数据   end-------------------------------------
				
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拆箱校验
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeApp_after")
	public void selectAccurateByCodeApp_after(HttpServletResponse response, String mcode, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		String location_code = zcBindAndUnbindService.selectByMaterielCode(mcode + ",", Long.parseLong(warehouse_id));
		if("SY".equals(location_code)){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			//根据mcode查询收货单详细
			CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
			if (codeMark != null) {
				List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
				if (receiveDetailList.size() > 0) {
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown(mcode, Long.parseLong(warehouse_id));
					if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
						receiveDetailList.get(0).getReceiveCode().add(codeMark);
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料未下架");
						jsonObject.put("data", receiveDetailList.get(0));
					} else {
						receiveDetailList.get(0).getReceiveCode().add(codeMark);
						
						receiveDetailList.get(0).setRcode(mcode);
						
						//传递数据到页面
						jsonObject.put("status", "1");
						jsonObject.put("message", "此物料已下架");
						jsonObject.put("data", receiveDetailList.get(0));
					}
				} else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "查询不到此条码");
					jsonObject.put("data", null);
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				/*codemark表中无此条码
				1.先在条码记录表中查询有没有，有，则表示此条码已出库。
				2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
				
				//根据条码在条码记录表中查询此条码的信息
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(mcode);
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {
					param.setWarehouse_id(Long.valueOf(warehouse_id));
					//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
					List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
					
					if(list2.size() > 0) {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码已出库或已拆箱");
						jsonObject.put("data", null);
					}else {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "该条码不属于本仓库");
						jsonObject.put("data", null);
					}
				}else {
					
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
					
				}
				
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 拆箱校验（新）
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeApp2")
	public void selectAccurateByCodeApp2(HttpServletResponse response, String mcode, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
		if (codeMark != null) {
			List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
			if (receiveDetailList.size() > 0) {
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown(mcode, Long.parseLong(warehouse_id));
				if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
					receiveDetailList.get(0).getReceiveCode().add(codeMark);
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "此物料未下架");
					jsonObject.put("data", receiveDetailList.get(0));
				} else {
					//根据物料id查询最早的批次
					String oldPici = ReceiveDetailService.selectOldPiciByMid(receiveDetailList.get(0).getMid());
					receiveDetailList.get(0).setOldPici(oldPici);
					receiveDetailList.get(0).getReceiveCode().add(codeMark);
					
					//传递数据到页面
					jsonObject.put("status", "1");
					jsonObject.put("message", "此物料已下架");
					jsonObject.put("data", receiveDetailList.get(0));
				}
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			/*codemark表中无此条码
			1.先在条码记录表中查询有没有，有，则表示此条码已出库。
			2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
			
			//根据条码在条码记录表中查询此条码的信息
			BarCodeOperation param = new BarCodeOperation();
			param.setBarCode(mcode);
			List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
			
			if(list.size() > 0) {
				param.setWarehouse_id(Long.valueOf(warehouse_id));
				//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
				List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
				
				if(list2.size() > 0) {
					//此条码已出库
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码已出库或已拆箱");
					jsonObject.put("data", null);
				}else {
					//此条码已出库
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "该条码不属于本仓库");
					jsonObject.put("data", null);
				}
			}else {
				
				//根据条码，在receivemark表中查询
				ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
				
				if(receiveMark != null) {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
					jsonObject.put("data", null);
				}else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "系统无此条码");
					jsonObject.put("data", null);
				}
				
			}
			
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 根据条码查询状态（紧急收货单）
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/urgencySelectAccurateByCodeApp")
	public void urgencySelectAccurateByCodeApp(HttpServletResponse response, String mcode, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		String location_code = zcBindAndUnbindService.selectByMaterielCode(mcode + ",", Long.parseLong(warehouse_id));
		if("SY".equals(location_code)){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			//根据mcode查询收货单详细
			CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
			if (codeMark != null) {
				List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
				if (receiveDetailList.size() > 0) {
					if (1 == receiveDetailList.get(0).getStatus()) {
						ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDownLocation(mcode,"DJ");
						if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
							receiveDetailList.get(0).getReceiveCode().add(codeMark);
							//传递数据到页面
							jsonObject.put("status", "0");
							jsonObject.put("message", "质检区无此条码");
							//jsonObject.put("data", receiveDetailList.get(0));
						} else {
							receiveDetailList.get(0).getReceiveCode().add(codeMark);
							//传递数据到页面
							jsonObject.put("status", "1");
							//jsonObject.put("message", "此物料已下架");
							jsonObject.put("data", receiveDetailList.get(0));
						}
					}else if(0 == receiveDetailList.get(0).getStatus()){
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料未质检");
						//jsonObject.put("data", null);
					}else{
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料已上架");
						//jsonObject.put("data", null);
					}
				} else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "查询不到此条码");
					jsonObject.put("data", null);
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				
				/*codemark表中无此条码
				1.先在条码记录表中查询有没有，有，则表示此条码已出库。
				2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
				
				//根据条码在条码记录表中查询此条码的信息
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(mcode);
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {
					param.setWarehouse_id(Long.valueOf(warehouse_id));
					//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
					List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
					
					if(list2.size() > 0) {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码已出库或已拆箱");
						jsonObject.put("data", null);
					}else {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "该条码不属于本仓库");
						jsonObject.put("data", null);
					}
				}else {
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 查询状态为1的收货单详细(盘点使用)
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeAppInventory")
	public void selectAccurateByCodeAppInventory(HttpServletResponse response, String mcode) {
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
		if (codeMark != null) {
			List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
			if (receiveDetailList.size() > 0) {
				receiveDetailList.get(0).getReceiveCode().add(codeMark);
				jsonObject.put("status", "1");
				jsonObject.put("data", receiveDetailList.get(0));
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询不到此条码");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 查询状态为0的质检表APP
	 * @param response
	 * lz2019年11月7日 17:27:46新增接收app传递过来的warehouse_id参数
	 */
	@RequestMapping("/queryReceiveDetailQualityAPP")
	public void queryReceiveDetailQualityAPP(HttpServletResponse response, String warehouse_id) {
		log.info("APP查询状态为0的质检表传过来的仓库id为：" + warehouse_id);
		CodeMark codeMark;
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		List<ReceiveDetailQuality> receiveDetailQualityList = ReceiveDetailService.queryReceiveDetailQualityAPP(Long.parseLong(warehouse_id));
		for (int i = 0; i < receiveDetailQualityList.size(); i++) {
			List codeMarkList = new ArrayList<>();
			//List<CodeMark> codeMark1 = ReceiveDetailService.queryCodeMarkById(receiveDetailQualityList.get(i).getRemark());
			List<CodeMark> codeMark1 = ReceiveDetailService.queryCodeMarkById(receiveDetailQualityList.get(i).getId() + "");
			for (int j = 0; j < codeMark1.size(); j++) {
				codeMark = new CodeMark();
				codeMark.setReceive_detail_id(codeMark1.get(j).getReceive_detail_id());
				codeMark.setNum(codeMark1.get(j).getNum());
				codeMark.setCode(codeMark1.get(j).getCode());
				codeMark.setIs_ng(codeMark1.get(j).getIs_ng());
				codeMarkList.add(codeMark);
			}
			receiveDetailQualityList.get(i).setReceiveCode(codeMarkList);
		}
		if (receiveDetailQualityList.size() > AFFECT_ROW) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", receiveDetailQualityList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("data", null);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("APP查询状态为0的质检表返回给app的参数条数：" + jsonObject.size());
			e.printStackTrace();
		}
	}

	/**
	 * 查询状态为1的质检表
	 * @param response
	 * lz2019年11月7日 17:27:46新增接收app传递过来的warehouse_id参数
	 */
	@RequestMapping("/queryReceiveDetailQualityAPP1")
	public void queryReceiveDetailQualityAPP1(HttpServletResponse response, String warehouse_id) {
		log.info("APP查询状态为1的质检表传过来的仓库id为：" + warehouse_id);
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		List<ReceiveDetailQuality> receiveDetailQualityList = ReceiveDetailService.queryReceiveDetailQualityAPP1(Long.parseLong(warehouse_id));
		if (receiveDetailQualityList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", receiveDetailQualityList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("data", null);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			log.info("APP查询状态为1的质检表返回给app的参数条数：" + jsonObject.size());
			e.printStackTrace();
		}
	}

	/**
     * 质检提交
     * @param json 质检实体
     * @param person 质检人
     * @param response
     * @param warehouse_id 仓库id
     */
    @RequestMapping("/updateReceiveDetailQualityAPP")
    public void updateReceiveDetailQualityAPP(String json, String person, HttpServletResponse response, String warehouse_id) {
        JSONObject jsonObject = new JSONObject();
        Integer affactRow = upService.updateReceiveDetailQualityAPP(json, person, warehouse_id);
        if (affactRow > AFFECT_ROW) {
            jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "质检完成");
        } else {
            jsonObject.put("status", "0");
            jsonObject.put("message", "质检失败");
            jsonObject.put("data", "0");
        }
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	/**
	 * 拆箱
	 * @param json1
	 * @param json2
	 * @param userId
	 * @param response          
	 * LZ新增warehouse_id参数   
	 */
	@RequestMapping("/devanning")
	public void devanning(String json1, String json2, String userId, HttpServletResponse response, String warehouse_id) {
		JSONObject jsonObject = new JSONObject();
		Gson gson = new Gson();
		try {
			//拆箱前
			List<CodeMark> codeMarkList1 = gson.fromJson(json1, new TypeToken<List<CodeMark>>() {}.getType());
			//拆箱后
			List<CodeMark> codeMarkList2 = gson.fromJson(json2, new TypeToken<List<CodeMark>>() {}.getType());
			//工作量
			List<Workload> workList = gson.fromJson(userId, new TypeToken<List<Workload>>() {}.getType());
			//删除缓存区
			
			//遍历查询是否有和剩余条码相同的条码
			int flag = 1;
			String codeArr3 = "";
			List<CodeMark> codeMarkList3 = materielService.queryAllCode(codeMarkList1.get(0).getCode());
			List<String> list = new ArrayList<>();
			for(CodeMark cm : codeMarkList1){
				list.add(cm.getCode());
			}
			
			List<String> list5 = new ArrayList<>();
			for(CodeMark cm : codeMarkList2){
				list5.add(cm.getCode());
			}
			
			list5.removeAll(list);
			
			for (String  c4 : list5) {
				for (CodeMark c3 : codeMarkList3) {
					if (c4.equals(c3.getCode())) {
						flag=0;
						codeArr3 += c4 + ",";
					}
				}
			}
			if(flag == 1) {
			
				//连雷明 修改
				//替换条码
				//1.1、找到旧条码中第一个条码的位置
				CodeMark codeMark = cancellingStockDetailService.queryCodeByCode(codeMarkList1.get(0).getCode());
				String code = codeMarkList1.get(0).getCode()+",";
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(code);
				if(zcMaterielAndTrayEntity != null){
					int afacct = unpackDetalService.devanningWork(codeMarkList1, codeMarkList2, workList, warehouse_id, codeMark, zcMaterielAndTrayEntity);
					if ( afacct > AFFECT_ROW) {
						jsonObject.put("status", "1");
						jsonObject.put("message", "");
						jsonObject.put("data", "提交成功");
					}else if (afacct == -1) {
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码已拆箱或已出库");
						jsonObject.put("data", "0");
					}else {
						jsonObject.put("status", "0");
						jsonObject.put("message", "提交失败");
						jsonObject.put("data", "0");
					}
				}else{
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "请扫正确条码");
					jsonObject.put("data", "0");
				}
			}else {
				jsonObject.put("status", "0");
				jsonObject.put("message", "输入的条码"+codeArr3+"与原条码重复");
				jsonObject.put("data", "0");
			}
			
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "精准拆箱错误");
			jsonObject.put("data", "0");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据精准码查询是否存在
	 * @param mcode
	 * @param response
	 */
	@RequestMapping("/queryRepeatAccurateByCodeApp")
	public void queryRepeatAccurateByCodeApp(String mcode, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		CodeMark codemark = ReceiveDetailService.queryRepeatAccurateByCodeApp(mcode);
		if (codemark != null) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "条码已使用");
			jsonObject.put("data", codemark.getCode());
		} else {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", mcode);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询有仓库操作员权限的人员
	 * @param response
	 */
	@RequestMapping("/queryRoleUser")
	public void queryRoleUser(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		List<String> userNmaeList = ReceiveDetailService.queryRoleUser();
		if (userNmaeList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", userNmaeList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			//jsonObject.put("data", "");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 将入库后的不良品入库
	 * @param json
	 * @param person
	 * @param response
	 */
	@RequestMapping("/ngInstock")
	public void ngInstock(String json, String person, HttpServletResponse response, String warehouse_id) {
		BarCodeConversionRecord record = new BarCodeConversionRecord();
		Gson gson = new Gson();
		JSONObject jsonObject = new JSONObject();
		List<CodeMark> codeMarkList = gson.fromJson(json, new TypeToken<List<CodeMark>>() {}.getType());
		for (CodeMark codeMark : codeMarkList) {
			//如果是良品
			if (codeMark.getIs_ng() == 0) {
				Long affact = ReceiveDetailService.updateIsngStatus(codeMark.getCode());
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				record.setMateriel_id(receiveDetailQuality.getMid());
				record.setMateriel_count(codeMark.getNum());
				record.setOperate_id(Long.parseLong(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				record.setOperate_time(sdf.format(new Date()));
				record.setPrefix_code(codeMark.getCode());
				record.setOperate_type("良品转不良品");
				record.setTrans_reason("");
				record.setImg_url("");
				//LZ新增warehouse_id字段
				record.setWarehouse_id(Long.parseLong(warehouse_id));
				//新增条码转换记录
				ReceiveDetailService.insertBarCodeConversionRecord(record);
				if (affact > AFFECT_ROW) {
					jsonObject.put("status", "1");
					jsonObject.put("data", "转换成功");
				} else {
					jsonObject.put("status", "0");
					jsonObject.put("message", "转换失败");
				}
			} else {
				//不良品转良品
				Long affact = ReceiveDetailService.updateIsngStatus1(codeMark.getCode());
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				record.setMateriel_id(receiveDetailQuality.getMid());
				record.setMateriel_count(codeMark.getNum());
				record.setOperate_id(Long.parseLong(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				record.setOperate_time(sdf.format(new Date()));
				record.setPrefix_code(codeMark.getCode());
				record.setOperate_type("不良品转良品");
				record.setTrans_reason("");
				record.setImg_url("");
				//LZ新增warehouse_id字段
				record.setWarehouse_id(Long.parseLong(warehouse_id));
				//新增条码转换记录
				ReceiveDetailService.insertBarCodeConversionRecord1(record);
				if (affact > AFFECT_ROW) {
					jsonObject.put("status", "1");
					jsonObject.put("data", "转换成功");
				} else {
					jsonObject.put("status", "0");
					jsonObject.put("message", "转换失败");
				}
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 良品不良品转换
	 * @param json
	 * @param person
	 * @param response
	 */
	@RequestMapping("/transCodeMarkStatus")
	public void transCodeMarkStatus(String json, String person, HttpServletResponse response) {
		Gson gson = new Gson();
		List<CodeMark> codeMarkList = gson.fromJson(json, new TypeToken<List<CodeMark>>() {}.getType());
		for (CodeMark codeMark : codeMarkList) {
			//根据条码修改条码状态
			Long affact = ReceiveDetailService.updateIsngStatus(codeMark.getCode());
			/*if (affact > 0) {
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				//1.首先去查询不良品库中该物料是否存在
				ZcRejectsWarehouseEntity zcRejectsWarehouseEntity = ReceiveDetailService.
						queryZcRejectsWarehouseEntityByMbatchAngMid(receiveDetailQuality);
				//如果存在
				if (zcRejectsWarehouseEntity != null) {
					int totality = zcRejectsWarehouseEntity.getTotality();
					totality = receiveDetailQuality.getNg_num() + totality;
					receiveDetailQuality.setNg_num(totality);
					ReceiveDetailService.updateZcRejectsWarehouseEntity(receiveDetailQuality);
				} else {
					receiveDetailQuality.setPerson(person);
					ReceiveDetailService.addZcRejectsWarehouseEntity(receiveDetailQuality);
				}
			}*/
		}
		JSONObject jsonObject = new JSONObject();
		List<String> userNmaeList = ReceiveDetailService.queryRoleUser();
		if (userNmaeList.size() > AFFECT_ROW) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "不良品入库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "不良品入库失败");
			jsonObject.put("data", "");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询状态为0的计数入库单
	 * @param response
	 */
	@RequestMapping("selectAllReceipt")
	public void selectAllReceipt(HttpServletResponse response){
		ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
		//未收货
		List<Receive> list = zcSimplificationInService.selectSimplificationInListAll(zcGeneralQueryEntity);
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > AFFECT_ROW) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 通过收货单号查详情（计数）
	 */
	@RequestMapping("selectReceiptDtailByNumber")
	public void selectReceiptDtailByNumber(String receiveNumber,HttpServletResponse response){
		ReceiveDetail param = new ReceiveDetail();
		param.setReceiveNumber(receiveNumber);
		List<ReceiveDetail> list = ReceiveDetailService.queryAllByMution(param );
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 收货提交(计数)
	 * @param Details 收货详情集合
	 * @param person 收货人
	 * @param sure_name 回收容器数量
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/submitReceipt")
	public void submitReceipt(String Details, String person, String sure_name, HttpServletResponse response, String warehouse_id){
		//初始化影响行数
		int affact1 = 0;
		Long affact = 0L;
		//json参数转化为实体集合
		Gson gson = new Gson();
		List<ReceiveDetail> receiveDetailList = gson.fromJson(Details, new TypeToken<List<ReceiveDetail>>() {}.getType());
		//遍历修改
		for (ReceiveDetail receiveDetail : receiveDetailList) {
			/*==================新表添加数据================*/
			//ReceiveDetailService.addReceiveDetailInstock(receiveDetail);
			/*==================修改收货详细表信息==========*/
			affact1 = ReceiveDetailService.update(receiveDetail);
			/*==================修改质检表信息==========*/
			//ReceiveDetailService.updateReceiveDetailQuality(receiveDetail);
			/*====================添加库存=======================*/
			int number = receiveDetail.getCodeNum();
//			ZcInventoryInfoEntity zcInventoryInfoEntity = upService.selectByMid2(receiveDetail.getMid() + "", receiveDetail.getPici());
			/************************llm 19.11.08 修改 start ***************************/
			ZcInventoryInfoEntity zcInventoryInfoEntity = upService.selectByMid2(receiveDetail.getMid() + "", receiveDetail.getPici(), warehouse_id);
			/************************llm 19.11.08 修改 end   ***************************/
			//1.如果查到
			if (zcInventoryInfoEntity != null) {
				int mNum = zcInventoryInfoEntity.getmNum();
				//1.如果是精准码,只存入总数
				mNum = number + mNum;
				//总数量（个数）
				zcInventoryInfoEntity.setmNum(mNum);
				affact = upService.editStockOnlyCount(zcInventoryInfoEntity);
			} else {
				ZcInventoryInfoEntity zcInventoryInfoEntity1 = new ZcInventoryInfoEntity();
				zcInventoryInfoEntity1.setMid(receiveDetail.getMid());
				zcInventoryInfoEntity1.setmNum(receiveDetail.getCodeNum());
				zcInventoryInfoEntity1.setmBatch(receiveDetail.getPici());
				zcInventoryInfoEntity1.setEnterPerson(Long.parseLong(person));
				affact = upService.insertStockOnlyCount(zcInventoryInfoEntity1);
			}
		}

		//获取收货单号
		ReceiveDetail receiveDetail = receiveDetailList.get(0);
		//更改一级状态  --为已收货
		Receive receive = new Receive();
		receive.setReceiveNumber(receiveDetail.getReceiveNumber());
		receive.setIsSimple("1");
		List<Receive> receives = ReceiveService.allByMution(receive);
		
		if(receives.size()  > 0) {
			Receive receive2 = receives.get(0);
			receive2.setState(1);
			receive2.setReceiveDate(DateUtil.dateFormat3());
			receive2.setReceiveName(person);
			receive2.setSendCompany(null);
			//回收容器数量
			receive2.setSureName(sure_name);
			ReceiveService.update(receive2);
		}
		JSONObject jsonObject = new JSONObject();
		if (affact > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", "提交成功");
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "提交失败");
		    jsonObject.put("data", "0");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据收货单单号查询所有ReceiveMark实体
	 * @param receiveId 收货单单号不是id
	 * @param mcode
	 * @param response
	 */
	@RequestMapping("/queryReceiveCodeByReceiveId")
	public void queryReceiveCodeByReceiveId(String receiveId, String mcode, HttpServletResponse response){
		CodeMark codeMark1 = new CodeMark();
		codeMark1.setCode(mcode);
		//1.先查询CodeMark，如果查到直接返回此条码已收货
		//2.先查询CodeMark，如果未查到，再去查ReceiveMark，还没查到，返回app"此条码不存在"
		//3.先查询CodeMark，如果未查到，再去查ReceiveMark，查到，返回ReceiveMark实体
		JSONObject jsonObject = new JSONObject();
		//根据条码查询CodeMark实体
		CodeMark codeMark = ReceiveDetailService.queryCodeMarkByCode(codeMark1);
		if (codeMark != null) {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "此物料已收货");
		} else {
			/*//根据收货单单号和条码查询ReceiveMark实体
			ReceiveMark receiveMark = ReceiveDetailService.queryReceiveCodeByReceiveId(receiveId, mcode);
			
			if (receiveMark != null) {
				//传递数据到页面
			    jsonObject.put("status", "1");
			    jsonObject.put("data", receiveMark);
			} else {
				//传递数据到页面
			    jsonObject.put("status", "0");
			    jsonObject.put("message", "此条码不存在");
			}*/
			//根据收货单id查询收货单
            Receive receive = ReceiveService.queryReceiveById(receiveId);
            if (receive != null) {
                //判断合并标识是否为空，如果不为空则表示此收货单为单据合并的收货单
                if(receive.getMerge_flag() != null) {
                    //根据条码查询ReceiveMark表中 有无此数据
                    ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
                    if (receiveMark != null) {
                        //传递数据到页面
                        jsonObject.put("status", "1");
                        jsonObject.put("data", receiveMark);
                    } else {
                        //传递数据到页面
                        jsonObject.put("status", "0");
                        jsonObject.put("message", "系统无此条码");
                    }
                } else {
                    //根据条码查询ReceiveMark表中 有无此数据
                    ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
                    if(receiveMark != null) {
                        //ReceiveMark表中 有 此数据
                        if(receiveMark.getReceiveDetail().getReceiveNumber() != null && receiveId != null) {
                            String receiveNumber = receiveMark.getReceiveDetail().getReceiveNumber();
                            if(receiveId.equals(receiveNumber)){
                                //传递数据到页面
                                jsonObject.put("status", "1");
                                jsonObject.put("data", receiveMark);
                            } else {
                                jsonObject.put("status", "0");
                                jsonObject.put("message", "此条码在"+receiveNumber+"收货单中");
                            }
                        }
                    } else {
                        //ReceiveMark表中 无 此数据
                        //传递数据到页面
                        jsonObject.put("status", "0");
                        jsonObject.put("message", "系统无此条码");
                    }
                }
            }
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分页查询条码转换记录
	 * @param response
	 * @param criteria
	 * @修改记录 LZ新增session获取当前登录人
	 */
	@RequestMapping("/queryBarCodeConversionRecordCriteria")
	public void queryBarCodeConversionRecordCriteria(HttpServletResponse response, LzQueryCriteria criteria, HttpSession session){
		//LZ新增仓库id字段
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		//LZ给keyword07参数赋值
		criteria.setKeyword07(warehouse_id + "");
		List<BarCodeConversionRecord> recordList = ReceiveDetailService.queryBarCodeConversionRecordCriteria(criteria);
		int count = ReceiveDetailService.countBarCodeConversionRecordCriteria(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(recordList);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 良品转不良品确认
	 * @param response
	 */
	@RequestMapping("/updateConfirm")
	public void updateConfirm(HttpServletResponse response, String id){
		Long affectRow = ReceiveDetailService.updateConfirm(Long.parseLong(id));
		if (affectRow > AFFECT_ROW) {
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, AFFECT_ROW);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查询条码是否存在
	 * @param response
	 * @param code 条码
	 */
	@RequestMapping("/queryLifeByCode")
	public void queryLifeByCode(HttpServletResponse response, String code){
		JSONObject jsonObject = new JSONObject();
		CodeMark codeMark = new CodeMark();
		codeMark.setCode(code);
		//根据条码查询CodeMark实体
		CodeMark cm = ReceiveDetailService.queryCodeMarkByCode(codeMark);
		if (cm == null) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("data", code);
		} else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "此条码已存在");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//---------------------------------------------------------jyy2019-12-18start---------------------------------------------------------
	
	/**
	 * 拆箱校验
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeApp")
	public void selectAccurateByCodeApp(HttpServletResponse response, String mcode, Long warehouse_id) {
		//日志
		log.info("bindAndUnbind/selectMaterielLocationByCodeAppDown.do（拆箱、出库、退库扫码校验）"
				+ "根据物料条码和仓库id查询物料所在位置接收参数：mcode="+mcode+",warehouse_id="+warehouse_id);
		
		JSONObject jsonObject = new JSONObject();
		
		try {
			//根据条码查询此条码所在托盘的信息
			List<TrayLocation> trayLocations = zcBindAndUnbindService.selectInfoByCode(mcode);
			
			if(trayLocations.size() > 1){
				//说明：codeMark表存在两个一样的条码  or 一个条码在两个托盘及库位上--数据错误--此条码数据错误，请联系管理员
				jsonObject.put("status", "0");
				jsonObject.put("message", "有重复条码，数据错误，请联系管理员");
			} else if(trayLocations.size() == 1){
				TrayLocation trayLocation = trayLocations.get(0);
				if(trayLocation.getWarehouse_id() != null) {
					if(warehouse_id.equals(trayLocation.getWarehouse_id())) {
						if( trayLocation.getLocation_code()!= null && !"".equals(trayLocation.getLocation_code()) ) {
							if(!"SY".equals(trayLocation.getLocation_code())) {
								//不在损溢区
								if( !"DJ".equals(trayLocation.getLocation_code()) ) {
									if("HC".equals(trayLocation.getLocation_code())) {
										//根据mcode查询收货单详细
										CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
										if(codeMark != null) {
											List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
											//数据没问题，返回此托盘所有条码信息 ：
											ReceiveDetail receiveDetail = receiveDetailList.get(0);
											receiveDetail.getReceiveCode().add(codeMark);
											receiveDetail.setRcode(mcode);
											
											jsonObject.put("status", "1");
											jsonObject.put("data", receiveDetail);
										}else {
											jsonObject.put("status", "0");
											jsonObject.put("message", "条码已出库，或已拆箱");
										}
									}else {//未下架
										jsonObject.put("status", "0");
										jsonObject.put("message", "此条码未下架");
									}
								}else {//在待上架区
									jsonObject.put("status", "0");
									jsonObject.put("message", "此条码在待上架区");
								}
							}else {//在损益区
								jsonObject.put("status", "0");
								jsonObject.put("message", "此条码在损益区");
							}
						}else {//条码所在库位为空
							jsonObject.put("status", "0");
							jsonObject.put("message", "此条码没有所属库位，数据错误，请联系管理员");
						}
					}else {//仓库id不匹配
						jsonObject.put("status", "0");
						jsonObject.put("message", "此条码不属于当前登录仓库");
					}
				}else {//此条码所在仓库为空（基本不会存在）
					jsonObject.put("status", "0");
					jsonObject.put("message", "此条码没有所属仓库，数据错误，请联系管理员");
				}
			} else {//查询数据为空，此条码不在托盘及库位上，可能没收货或已出库或已拆箱
				//根据条码查询操作记录表中的最后一条记录
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(mcode);
				param.setWarehouse_id(warehouse_id);
				//根据条码和仓库id和条码在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {//此条码已出库或已拆箱
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码已出库或已拆箱");
					jsonObject.put("data", null);
				}else {//操作记录中没有
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(mcode);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
				}
			}
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "条码校验方法异常");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			log.error("条码校验方法异常");	
			e.printStackTrace();
		}
		
		
	}
	//---------------------------------------------------------jyy2019-12-18end-----------------------------------------------------------
}
